package org.jeecg.modules.pdd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pdd.pop.sdk.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.Date.DateUtil;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.TbUserVip;
import org.jeecg.modules.appuser.entity.TbUserWallet;
import org.jeecg.modules.appuser.entity.TbUserWalletDetail;
import org.jeecg.modules.appuser.service.ITbUserIntegralService;
import org.jeecg.modules.appuser.service.ITbUserVipService;
import org.jeecg.modules.appuser.service.ITbUserWalletDetailService;
import org.jeecg.modules.appuser.service.ITbUserWalletService;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.pdd.entity.PddGoodsOrder;
import org.jeecg.modules.pdd.entity.PddPromotion;
import org.jeecg.modules.pdd.mapper.PddGoodsOrderMapper;
import org.jeecg.modules.pdd.service.IPddGoodsOrderService;
import org.jeecg.modules.pdd.service.IPddPromotionService;
import org.jeecg.modules.pdd.util.DingDanXiaUtil;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Description: 拼多多订单管理
 * @Author: jeecg-boot
 * @Date: 2020-05-21
 * @Version: V1.0
 */
@Service
@Slf4j
public class PddGoodsOrderServiceImpl extends ServiceImpl<PddGoodsOrderMapper, PddGoodsOrder> implements IPddGoodsOrderService {

    @Autowired
    private IPddPromotionService pddPromotionService;
    @Autowired
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserVipService tbUserVipService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;

    @Autowired
    private ITbUserIntegralService tbUserIntegralService;

    @Autowired
    private ISysDictService sysDictService;

    @Override
    public void queryOrderByTask(String parameter) throws Exception {

        //得到默认配置的时间
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("order_start_time");
        String daynum = "0";
        if (null != dictModelList && dictModelList.size() > 0) {
            daynum = dictModelList.get(0).getValue();
        }
        if (!StringUtils.isEmpty(parameter)) {
            daynum = parameter;
        }
        log.info( DateUtil.getTenBeforeDate(Integer.valueOf(daynum))+"pdd   11 start_time" + Integer.valueOf(daynum));
        String start_time = DateUtil.getTenBeforeDate(Integer.valueOf(daynum));
        String end_time = DateUtil.getEndBeforeDate(Integer.valueOf(daynum));
        log.info("pdd    start_time" + start_time);
        log.info("pdd end_time" + start_time);
        String json = DingDanXiaUtil.getOrders(DateUtil.dateStringToLong(start_time), DateUtil.dateStringToLong(end_time));

        if (!StringUtils.isEmpty(json)) {
            JSONObject jsonObject = JSON.parseObject(json);

            String goodsJsonList = jsonObject.getString("data");
            List<PddGoodsOrder> pddGoodsOrderList = JSON.parseArray(goodsJsonList, PddGoodsOrder.class);
            if (null != pddGoodsOrderList && pddGoodsOrderList.size() > 0) {

                for (PddGoodsOrder pddGoodsOrder : pddGoodsOrderList) {
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("order_sn", pddGoodsOrder.getOrderSn());
                    PddGoodsOrder pddGoodsOrder1 = this.getOne(queryWrapper);
                    if (null == pddGoodsOrder1) {
                        save(pddGoodsOrder);
                    } else {
                        pddGoodsOrder1.setOrderStatus(pddGoodsOrder.getOrderStatus());
                        this.update(pddGoodsOrder1, queryWrapper);
                    }
                    //已确认
                    if (5 == pddGoodsOrder.getOrderStatus()) {
                        //返佣
                        String pid = pddGoodsOrder.getPId();
                        //查询用户
                        if (pddGoodsOrder1.getRebateStatus() == 0) {
                            TbMnUser tbMnUser = pddPromotionService.getTbmnUserByPid(pid);
                            //返佣三级
                            int rebate_layer_num = 3;
                            RebateUser(pddGoodsOrder1, tbMnUser, rebate_layer_num);
                            //TODO 增加个人积分一次
                            Map<String, Object> resultData1 = tbUserIntegralService.doActionTask(tbMnUser.getId(), TaskNamesConstant.Task_SELF_PURCHASE_GOODS);
                            log.info(resultData1.toString());
                        }
                    }
                }
            }
        }
    }

    //升级用户等级
    private boolean upgradeUserGrade(TbMnUser tbMnUser) {
        BigDecimal profit = new BigDecimal(0);
        if (null != tbMnUser) {
            QueryWrapper userWalletQueryWrapper = new QueryWrapper();
            userWalletQueryWrapper.eq("user_id", tbMnUser.getId());
            userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
            List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
            if (null != tbUserWalletDetailList && tbUserWalletDetailList.size() > 0) {
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit = profit.add(tbUserWalletDetail.getPayNumber());
                }
            }
            log.info(tbMnUser.getPhone() + "用户升级---------------------------------->" + profit);
            //得到上一等级
            TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
            int next_srot = tbUserVip.getSort() + 1;
            QueryWrapper vipQueryWrapper = new QueryWrapper();
            vipQueryWrapper.eq("sort", next_srot);
            TbUserVip next_tbUserVip = tbUserVipService.getOne(vipQueryWrapper);
            if (null == next_tbUserVip) {
                log.info("你已经是最高等级了");
            } else {
                BigDecimal next_tbUserVipBalanceMin = next_tbUserVip.getInviteProfit();
                log.info(tbMnUser.getPhone() + "用户升级------profit.compareTo(next_tbUserVipBalanceMin---->" + profit.compareTo(next_tbUserVipBalanceMin));
                if (profit.compareTo(next_tbUserVipBalanceMin) >= 0) {
                    //升级
                    tbMnUser.setVipId(next_tbUserVip.getId());
                    tbMnUser.setVipName(next_tbUserVip.getVipName());
                    String bigDecimal = next_tbUserVip.getFirstRebate().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
                    tbMnUser.setOwnRate(bigDecimal);
                    tbMnUserService.updateById(tbMnUser);
                    log.info(tbMnUser.getPhone() + "用户升级---------完成------------------------->\n");
                    log.info("{}升级成功,手机号码{}", tbMnUser.getAccount(), tbMnUser.getPhone());
                    return true;
                }
            }
        }

        return false;
    }

    private void RebateUser(PddGoodsOrder pddGoodsOrder1, TbMnUser tbMnUser, int rebate_layer_num) {

        if (rebate_layer_num > 0) {
            if (null != tbMnUser) {
                //查询它的被邀请人,进行返佣
                TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
                BigDecimal firstRebate = null;
                if (rebate_layer_num == 3) {
                    firstRebate = tbUserVip.getFirstRebate();
                }
                if (rebate_layer_num == 2) {
                    firstRebate = tbUserVip.getSecondRebate();
                }
                if (rebate_layer_num == 1) {
                    firstRebate = tbUserVip.getThirdRebate();
                }
                Long promotionRate = pddGoodsOrder1.getPromotionAmount();
                double promotionRate_double = promotionRate / 100d;
                BigDecimal totalCommissionFeedec = new BigDecimal(promotionRate_double);
                BigDecimal upperFirstFee = firstRebate.multiply(totalCommissionFeedec);
                TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(tbMnUser.getId());
                synchronized (tbUserWallet) {
                    BigDecimal upperFirstWalletBalance = tbUserWallet.getBalance();
                    BigDecimal new_upperFirstWalletBalance = upperFirstWalletBalance.add(upperFirstFee);
                    tbUserWallet.setBalance(new_upperFirstWalletBalance);

                    if (saveUserWalletDetail(tbUserWallet, upperFirstFee, tbMnUser.getId())) {
                        //资产更新成功
                        if (tbUserWalletService.updateById(tbUserWallet)) {
                            rebate_layer_num = rebate_layer_num - 1;
                            TbMnUser inviteesUpperFirst = tbMnUserService.getInviteesUpperFirst(tbMnUser);
                            //得到用户等级
                            if (null != inviteesUpperFirst) {
                                RebateUser(pddGoodsOrder1, inviteesUpperFirst, rebate_layer_num);
                            }
                        }
                    }
                }
            }
            //用户升级
            upgradeUserGrade(tbMnUser);
        }
    }

    private boolean saveUserWalletDetail(TbUserWallet tbUserWallet, BigDecimal newBalance, String fromUserId) {
        TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
        tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_REBATE);
        tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserWalletDetail.setPayNumber(newBalance);
        tbUserWalletDetail.setWalletId(tbUserWallet.getId());
        tbUserWalletDetail.setUserId(tbUserWallet.getUserId());
        tbUserWalletDetail.setFromUser(fromUserId);
        tbUserWalletDetail.setBalance(tbUserWallet.getBalance());
        tbUserWalletDetailService.save(tbUserWalletDetail);
        return true;
    }


    //order_status订单状态： -1 未支付; 0-已支付；1-已成团；2-确认收货；3-审核成功；4-审核失败（不可提现）；5-已经结算；8-非多多进宝商品（无佣金订单）
    @Override
    public Result<?> queryOrders(PddGoodsOrder pddGoodsOrder, String user_id, Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryWrapper pddqueryWrapper = new QueryWrapper();
        pddqueryWrapper.eq("user_id", user_id);
        PddPromotion pddPromotion = pddPromotionService.getOne(pddqueryWrapper);
        Page<PddGoodsOrder> page = new Page<>(pageNo, pageSize);

        QueryWrapper<PddGoodsOrder> queryWrapperOrder = QueryGenerator.initQueryWrapper(pddGoodsOrder, request.getParameterMap());
        queryWrapperOrder.eq("p_id", pddPromotion.getPid());
//        pddGoodsOrder.setPId(pddGoodsOrder.getPId());
//        IPage<PddGoodsOrder> pageList = this.queryOrdersPages(page, pddGoodsOrder);

        List<PddGoodsOrder> pageList = this.baseMapper.selectList(queryWrapperOrder);
        TbMnUser tbMnUser = tbMnUserService.getById(user_id);
        TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
        if (null != pageList && pageList.size() > 0) {
            for (PddGoodsOrder goodsOrder : pageList) {
                BigDecimal firstRebate = tbUserVip.getFirstRebate();
                Long orderAmount = goodsOrder.getPromotionAmount();
                BigDecimal orderAmountDig = new BigDecimal(orderAmount);
                BigDecimal neworderAmountDig = orderAmountDig.multiply(firstRebate);
                goodsOrder.setPromotionAmount(neworderAmountDig.longValue());
            }
        }


        return Result.ok(pageList);
    }


    public IPage<PddGoodsOrder> queryOrdersPages(Page<PddGoodsOrder> page, PddGoodsOrder pddGoodsOrder) {
        return page.setRecords(this.baseMapper.queryOrdersPages(page, pddGoodsOrder));

    }
}


